import {Component, ViewChild} from "@angular/core";
import {Storage} from "@ionic/storage";

import {IonicApp, Keyboard, Nav, Platform, ToastController} from "ionic-angular";
import {SplashScreen} from "@ionic-native/splash-screen";

import {TabsPage} from "../pages/tabs/tabs";
import {StatusBar} from "@ionic-native/status-bar";
import {LoginFormData} from "../pages/login/login.form.data";
import {UserData} from "../common/user.data";
import {TutorialPage} from "../pages/tutorial/tutorial";
import {UserService} from "../service/user/user.service";


@Component({
  templateUrl: 'app.template.html',
  providers: []
})
export class ConferenceApp {
  rootPage: any = TabsPage;
  @ViewChild('mainContent') nav: Nav;
  backButtonPressed: boolean = false;  //用于判断返回键是否触发

  private loginFormData: LoginFormData = {};

  constructor(private platform: Platform,
              private statusBar: StatusBar,
              private ionicApp: IonicApp,
              private keybord: Keyboard,
              private user: UserData,
              private toastCtrl: ToastController,
              private splashScreen: SplashScreen,
              private userService: UserService,
              private storage: Storage) {
    this.storage.get('hasSeenTutorial')
      .then((hasSeenTutorial) => {
        if (hasSeenTutorial) {
          this.rootPage = TabsPage;
        } else {
          this.rootPage = TutorialPage;
        }
      });


    this.storage.get("user").then(value => {
      if (!value) return;
      this.loginFormData.type = 'PASSWORD';
      this.loginFormData.cellphone = value.cellphone;
      this.loginFormData.password = value.password;
      this.userService.login(this.loginFormData).subscribe(res => {
        if (res.status === "SUCCESS") {
          console.debug("用户自动登录成功");
          this.storage.set("user", res.data.userEntity);
          this.storage.set("oauthToken", res.data.oauthToken);
          this.user.token = res.data.oauthToken;
          this.user.user = res.data.userEntity;
          this.user.user.password = this.loginFormData.password;
        } else {
          console.warn("用户自动登录失败 :" + res);
          this.storage.remove("user");
          this.storage.remove("oauthToken");
        }
      }, error => {
        console.log("用户自动登录失败 :" + error);
        this.storage.remove("user");
        this.storage.remove("oauthToken");
      });
    });
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.registerBackButtonAction();
    });
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      if (this.keybord.isOpen()) {
        this.keybord.close();
        return;
      }
      //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
      this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() || this.ionicApp._overlayPortal.getActive()
      let activePortal = this.ionicApp._modalPortal.getActive();
      if (activePortal) {
        activePortal.dismiss().catch(() => {
        });
        activePortal.onDidDismiss(() => {
        });
        return;
      }
      let viewController = this.nav.getActive();
      let tabs = viewController.instance.tabs;
      let activeNav = tabs.getSelected();
      return activeNav.canGoBack() ? activeNav.pop() : this.showExit()
    }, 1);
  }

  //双击退出提示框
  showExit() {
    if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'top'
      }).present();
      this.backButtonPressed = true;
      setTimeout(() => this.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
    }
  }
}
